package com.delianna.bwt.data;

//Original class created by Sergi Juanola
//http://www.flexjockey.com/2011/03/create-a-pretty-simple-cache-for-android/

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;

import android.os.Environment;
import android.util.Log;

/**
 * @author Delio Castillo (jangeador@gmail.com)
 * 
 */
public class CacheStore {
	private static CacheStore INSTANCE = null;
	private static final String cacheDir = "/Android/data/com.delianna/cache/";
	private static final String defaultFileName = "bwt.xml";

	private CacheStore() {
		File fullCacheDir = new File(Environment.getExternalStorageDirectory()
				.toString(), cacheDir);
		if (!fullCacheDir.exists()) {
			Log.i("CACHE", "Directory doesn't exist");
			cleanCacheStart();
			return;
		}
	}

	public void cleanCacheStart() {
		File fullCacheDir = new File(Environment.getExternalStorageDirectory()
				.toString(), cacheDir);
		fullCacheDir.mkdirs();
		
		File noMedia = new File(fullCacheDir.toString(), ".nomedia");
		try {
			this.DeleteRecursive(fullCacheDir);
			Log.i("CACHE", "Cache files deleted");
			noMedia.createNewFile();
			Log.i("CACHE", "Cache created");
		} catch (IOException e) {
			Log.i("CACHE", "Couldn't create .nomedia file");
			e.printStackTrace();
		}
	}

	private synchronized static void createInstance() {
		if (INSTANCE == null) {
			INSTANCE = new CacheStore();
		}
	}

	public static CacheStore getInstance() {
		if (INSTANCE == null)
			createInstance();
		return INSTANCE;
	}

	public void saveCacheFile(String fileContent) {
		File fullCacheDir = new File(Environment.getExternalStorageDirectory()
				.toString(), cacheDir);
		String fileLocalName = defaultFileName;
		File fileUri = new File(fullCacheDir.toString(), fileLocalName);
		FileOutputStream outStream = null;
		try {
			outStream = new FileOutputStream(fileUri);
			fileContent = outStream.toString();
			outStream.flush();
			outStream.close();
			Log.i("CACHE", "Saved file " + fileUri.getName()
					+ " (which is now " + fileUri.toString() + ") correctly");
		} catch (FileNotFoundException e) {
			Log.i("CACHE", "Error: File " + fileUri + " was not found!");
			e.printStackTrace();
		} catch (IOException e) {
			Log.i("CACHE", "Error: File could not be stuffed!");
			e.printStackTrace();
		}
	}
	
	public boolean deleteCacheFile(File fileUri) {
			return fileUri.delete();
	}

	public void saveCacheFileFromURL(String DownloadURL, String fileName) {
		File fullCacheDir = new File(Environment.getExternalStorageDirectory()
				.toString(), cacheDir);
		String fileLocalName = defaultFileName;
		File fileUri = new File(fullCacheDir.toString(), fileLocalName);
		DownloadFromUrl(DownloadURL, fileUri);

	}

	public File getCacheFile(String cacheUri) {
		File fullCacheDir = new File(Environment.getExternalStorageDirectory()
				.toString(), cacheDir);
		File fileUri = new File(fullCacheDir.toString(), cacheUri);
		if (fileUri.exists())
			return fileUri;
		else
			return null;
	}

	private void DownloadFromUrl(String DownloadUrl, File fileUri) {

		try {

			URL url = new URL(DownloadUrl); // you can write here any link
			File file = fileUri;

			long startTime = System.currentTimeMillis();
			Log.d("DownloadManager", "download begining");
			Log.d("DownloadManager", "download url:" + url);
			Log.d("DownloadManager",
					"downloaded file name:" + fileUri.getName());

			BufferedReader in = new BufferedReader(new InputStreamReader(
					url.openStream(), "ISO-8859-1"));

			FileOutputStream fos = new FileOutputStream(file);
			BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
					fos, "ISO-8859-1"));

			int i;
			int count = 0;
			char c = ' ';
			do {
				i = in.read();
				if (i != -1) {
					c = (char) i;
					writer.write(c);
					count++;
				}
			} while (i != -1);

			Log.d("FILE_CACHE", "Count of chars is " + count + " " + c);
			in.close();
			writer.flush();
			writer.close();

			Log.d("DownloadManager",
					"download ready in"
							+ ((System.currentTimeMillis() - startTime) / 1000)
							+ " sec");

		} catch (IOException e) {
			Log.d("DownloadManager", "Error: " + e);
		}
	}
	
	private void DeleteRecursive(File fileOrDirectory) {
	    if (fileOrDirectory.isDirectory())
	        for (File child : fileOrDirectory.listFiles())
	            DeleteRecursive(child);

	    fileOrDirectory.delete();
	}
}
